<template>
  <el-row class="gap2" v-loading="formLoading">
    <el-col :span="8">
      <ContentWrap class="h-590px !overflow-y-auto">
        <el-tree
          ref="treeRef"
          :data="treeData"
          :expand-on-click-node="false"
          :props="treeProps"
          default-expand-all
          highlight-current
          node-key="id"
          @node-click="handleNodeClick"
        />
      </ContentWrap>
    </el-col>
    <el-col :span="15">
      <el-transfer
        :model-value="props.modelValue"
        @update:model-value="updateSelectedUserIds"
        :titles="['未选', '已选']"
        filterable
        filter-placeholder="搜索成员"
        :data="transferUserList"
        :props="{ label: 'nickname', key: 'id' }"
      />
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'

// 定义组件属性
const props: any = defineProps({
  // 树形数据
  treeData: {
    type: Array,
    required: true
  },
  // 树形配置属性
  treeProps: {
    type: Object,
    required: true
  },
  // 所有用户列表
  userList: {
    type: Array,
    required: true
  },
  // 当前过滤后的用户列表
  filteredUserList: {
    type: Array,
    required: true
  },
  // 选中的用户ID列表
  modelValue: {
    type: Array,
    default: () => []
  },
  // 加载状态
  formLoading: {
    type: Boolean,
    default: false
  }
})

// 定义事件
const emit = defineEmits(['node-click', 'update:modelValue'])

// 引用
const treeRef = ref()

// 计算属性：合并已选择的用户和当前过滤后的用户
const transferUserList: any = computed(() => {
  // 1.1 获取所有已选择的用户
  const selectedUsers = props.userList.filter((user: any) => props.modelValue.includes(user.id))

  // 1.2 获取当前过滤后的未选择用户
  const filteredUnselectedUsers = props.filteredUserList.filter(
    (user: any) => !props.modelValue.includes(user.id)
  )

  // 2. 合并并去重
  return [...selectedUsers, ...filteredUnselectedUsers]
})

// 处理节点被点击
const handleNodeClick = (row: { [key: string]: any }) => {
  emit('node-click', row)
}

// 更新选中的用户ID列表
const updateSelectedUserIds = (newIds: any[]) => {
  emit('update:modelValue', newIds)
}

// 暴露方法给父组件
defineExpose({
  treeRef,
  updateSelectedUserIds
})
</script>

<style lang="scss" scoped>
:deep() {
  .el-tree-node {
    white-space: unset;

    .el-tree-node__content {
      height: fit-content;
      min-height: var(--el-tree-node-content-height);
      padding: 1px 0;
    }
  }

  .el-transfer {
    --el-transfer-panel-body-height: 550px;

    display: flex;
  }

  .el-transfer__buttons {
    display: flex !important;
    flex-direction: column-reverse;
    justify-content: center;
    gap: 20px;

    .el-transfer__button:nth-child(2) {
      margin: 0;
    }
  }
}
</style>
